<?php
namespace App\Libs\DB;
class BasePdo extends \App\Libs\Base\Singleton
{
    private $connections = array();
	private $useMaster = false;
    protected $__DATABASE__;
    public static function __callStatic($method, $args) {
        return call_user_func_array(array(self::instance(), $method), $args);
    }

    public function __call($method, $args) {
        return call_user_func_array(array($this, $method), $args);
    }
	public function useMaster() {
		$this->useMaster = true;
	}

	public function useSlave() {
		$this->useMaster = false;
	}
	
	protected function begin() {
		$this->useMaster();
		$connection = $this->getConn();
		$connection->begin();
	}

	protected function commit() {
		$connection = $this->getConn();
		$connection->commit();
		$this->useSlave();
	}

	protected function rollback() {
		$connection = $this->getConn();
		$connection->rollback();
		$this->useSlave();
	}

    /**
     * 查询第一条数据第一列的值
     */
    protected function scalar($sql, $params = array()) {
        $row = $this->find($sql, $params);
        return empty($row) ? NULL : array_pop($row);
    }

    /**
     * 查询一行数据
     */
    protected function find($sql, $params = array(), $types = array()) {
        $connection = $this->getConn();
        return $connection->fetchOne($sql, \Phalcon\Db::FETCH_ASSOC, $params, $types);
    }

    /**
     * 查询所有数据
     */
    protected function findAll($sql, $params = array(), $types = array()) {
        $connection = $this->getConn();
        return $connection->fetchAll($sql, \Phalcon\Db::FETCH_ASSOC, $params, $types);
    }

    /**
     *
     * @param $values = array( k => v)
     * @param $conditions = array(
     *             'conditions' => '',
     *             'bind' => array(),
     *         )
     */
    protected function update($table, $values = array(), $conditions = array()) {
        $connection = $this->getConn('MASTER');

        $connection->update($table, array_keys($values), array_values($values), $conditions);
        return $connection->affectedRows();
    }

    protected function write($sql, $params) {
        $connection = $this->getConn('MASTER');
        $connection->execute($sql, $params);
        return $connection->affectedRows();
    }

    /**
     *
     * 一次插入一条数据
     */
    protected function insert($table, $values) {
        $connection = $this->getConn('MASTER');
        $connection->insert($table, array_values($values), array_keys($values));
        return $connection->lastInsertId();
    }

    protected function delete($table, $conditions) {
        $connection = $this->getConn('MASTER');
        $connection->delete($table, $conditions);
        return $connection->affectedRows();
    }

    protected function getConn($type = 'SLAVE', $force = FALSE) {
		if ($this->useMaster) {
			$type = 'MASTER';
		}
        if ( ! empty($this->connections[$this->__DATABASE__ . ':' . $type]) && (! $force)) {
            return $this->connections[$this->__DATABASE__ . ':' . $type];
        }
        if ($type === 'SLAVE') {
            $config = $this->getSlaveConf();
        } else {
            $config = $this->getMasterConf();
        }
        $config['dbname'] = $this->__DATABASE__;
        $db = new \Phalcon\Db\Adapter\Pdo\Mysql($config);
        $this->connections[$this->__DATABASE__ . ':' . $type] = $db;
        return $db;
    }

    protected function getMasterConf() {
        $confs = \App\Libs\Base\Config::instance()->mysql;
        return $confs[$this->__DATABASE__]['MASTER'];
    }

    protected function getSlaveConf() {
        $confs = \App\Libs\Base\Config::instance()->mysql;
        $confs = $confs[$this->__DATABASE__]['SLAVES'];
        $index = mt_rand(0, count($confs) - 1);
        return $confs[$index];
    }
}

